#!/usr/bin/env python3
"""
Local development server startup script for Manga Colorizer
Runs without Docker for testing purposes
"""

import os
import sys
import subprocess
import time
import signal
import threading
from pathlib import Path

# Add server directory to Python path
server_path = Path(__file__).parent.parent / "server"
sys.path.insert(0, str(server_path))

# Environment setup
os.environ.update({
    "DATABASE_URL": "sqlite:///./test.db",
    "REDIS_URL": "redis://localhost:6379/0",
    "STORAGE_TYPE": "local",
    "MODEL_NAME": "runwayml/stable-diffusion-v1-5",
    "CONTROLNET_MODEL": "lllyasviel/sd-controlnet-canny",
    "DEVICE": "cpu",  # Use CPU for local testing
    "MAX_FILE_SIZE": "10485760",  # 10MB
    "ALLOWED_EXTENSIONS": "png,jpg,jpeg,webp",
    "MODEL_PATH": "./models",
    "UPLOAD_PATH": "./uploads"
})

# Create necessary directories
for dir_name in ["models", "uploads", "logs"]:
    (server_path / dir_name).mkdir(exist_ok=True)

class LocalServerManager:
    def __init__(self):
        self.processes = []
        self.running = True
        
    def install_dependencies(self):
        """Install Python dependencies"""
        print("📦 Installing Python dependencies...")
        try:
            subprocess.run([
                sys.executable, "-m", "pip", "install", "-r", 
                str(server_path / "requirements.txt")
            ], check=True)
            print("✅ Dependencies installed successfully")
            return True
        except subprocess.CalledProcessError as e:
            print(f"❌ Failed to install dependencies: {e}")
            return False
    
    def check_redis(self):
        """Check if Redis is available"""
        try:
            import redis
            r = redis.from_url("redis://localhost:6379/0")
            r.ping()
            print("✅ Redis is running")
            return True
        except:
            print("⚠️  Redis not found, using in-memory storage")
            return False
    
    def start_fastapi_server(self):
        """Start FastAPI server"""
        print("🚀 Starting FastAPI server...")
        try:
            from server.main import app
            import uvicorn
            
            # Start server on port 8000 (or next available)
            port = 8000
            for p in range(8000, 8010):
                try:
                    import socket
                    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    s.bind(('localhost', p))
                    s.close()
                    port = p
                    break
                except:
                    continue
            
            print(f"🌐 Server starting on http://localhost:{port}")
            print(f"📚 API docs at http://localhost:{port}/docs")
            
            uvicorn.run(
                "server.main:app",
                host="0.0.0.0",
                port=port,
                reload=True,
                log_level="info"
            )
            
        except Exception as e:
            print(f"❌ Failed to start server: {e}")
            return False
    
    def create_test_environment(self):
        """Create test environment"""
        print("🧪 Setting up test environment...")
        
        # Create test directories
        test_dirs = ["uploads/original", "uploads/colored", "logs"]
        for dir_path in test_dirs:
            (server_path / dir_path).mkdir(parents=True, exist_ok=True)
        
        # Create test database
        import sqlite3
        conn = sqlite3.connect(str(server_path / "test.db"))
        conn.execute("""
            CREATE TABLE IF NOT EXISTS tasks (
                id TEXT PRIMARY KEY,
                status TEXT,
                original_path TEXT,
                colored_path TEXT,
                created_at TIMESTAMP,
                completed_at TIMESTAMP,
                error_message TEXT
            )
        """)
        conn.commit()
        conn.close()
        
        print("✅ Test environment ready")
    
    def run_health_check(self):
        """Run health check after startup"""
        time.sleep(5)  # Wait for server to start
        try:
            import requests
            response = requests.get("http://localhost:8000/api/v1/health", timeout=10)
            if response.status_code == 200:
                print("✅ Health check passed")
                return True
            else:
                print(f"❌ Health check failed: {response.status_code}")
                return False
        except Exception as e:
            print(f"❌ Health check error: {e}")
            return False
    
    def signal_handler(self, signum, frame):
        """Handle shutdown signals"""
        print("\n🛑 Shutting down...")
        self.running = False
        sys.exit(0)
    
    def start(self):
        """Start the local development environment"""
        print("🎨 Manga Colorizer - Local Development Server")
        print("=" * 50)
        
        # Setup signal handlers
        signal.signal(signal.SIGINT, self.signal_handler)
        signal.signal(signal.SIGTERM, self.signal_handler)
        
        # Check prerequisites
        if not self.install_dependencies():
            return False
        
        self.create_test_environment()
        
        # Check Redis (optional)
        redis_available = self.check_redis()
        if not redis_available:
            print("⚠️  Redis not available - using in-memory storage")
        
        # Start server
        print("\n🚀 Starting server...")
        print("Press Ctrl+C to stop")
        
        try:
            self.start_fastapi_server()
        except KeyboardInterrupt:
            print("\n🛑 Server stopped by user")
        except Exception as e:
            print(f"❌ Server error: {e}")
        
        return True


if __name__ == "__main__":
    manager = LocalServerManager()
    success = manager.start()
    sys.exit(0 if success else 1)
